import { EyeOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumnType, ProCoreActionType } from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { message, Image, Form, Popconfirm, Modal, Button as PCButton, Tooltip } from 'antd';
import React, { memo, useCallback, useMemo, useRef, useState } from 'react';
import type { TableListItem, TableListPagination } from './data';
import { addArticle, getPayMethodPage, batchDelArticle, updateArticle } from './service';
import { useEventListener, useSize } from 'ahooks'
import { Input, Stepper, TextArea, Button, Card, Space, List, Dialog, Toast } from 'antd-mobile'
import './index.less'
import CustomPicker from '@/components/MobileForm/CustomPicker';
import mobileRender from '@/utils/mobileRender';
import CustomCalendarPicker from '@/components/MobileForm/CustomCalendarPicker';
import pcRender from '@/utils/pcRender';
import dayjs from 'dayjs';
import MobileTableItem from '@/components/MobileTableItem/MobileTableItem';
import mobileRun from '@/utils/mobileRun';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const [windowWidth, setWindowWidth] = useState(window.innerWidth)
  const [editForm] = Form.useForm()
  const [addForm] = Form.useForm()
  const [addOpen, setAddOpen] = useState(false)
  const [editOpen, setEditOpen] = useState(false)
  const customTabRef = useRef(null)
  const size = useSize(customTabRef)
  const tableWidth = size?.width

  const CustomRow = useCallback((props: any) => {
    return <Card className='custom-table-row'
      style={{
        width: tableWidth,
        fontSize: 17,
        overflow: 'hidden',
        position: 'relative',
        marginBottom: 10
      }}
      bodyStyle={{ width: '100%' }}
      onClick={() => {

      }}>
      <Space style={{ width: '100%' }} direction='vertical'>
        {props?.children}
      </Space>
    </Card>
  }, [tableWidth])

  useEventListener('resize', (e: any) => {
    // console.log(e?.currentTarget?.innerWidth);
    setWindowWidth(e?.currentTarget?.innerWidth)
  });

  const onDelRecordItem = async (record: any) => {
    const hide = mobileRun(windowWidth, () => Toast.show({
      icon: 'loading',
      content: '正在删除…',
    }), () => message.loading('正在删除'));

    try {
      const res = await batchDelArticle({
        ids: [record?.id]
      })
      if (typeof hide === 'function') {
        hide();
      } else {
        hide.close?.()
      }
      if (res.code === 0) {
        mobileRun(windowWidth, () => Toast.show({
          icon: 'success',
          content: '删除成功，即将刷新',
        }), () => message.success('删除成功，即将刷新'));
        actionRef.current?.reload()
        return true
      } else {
        mobileRun(windowWidth, () => Toast.show({
          icon: 'fail',
          content: '删除失败，请重试',
        }), () => message.error('删除失败，请重试'));
        return false;
      }
    } catch (e) {
      if (typeof hide === 'function') {
        hide();
      } else {
        hide.close?.()
      }
      mobileRun(windowWidth, () => Toast.show({
        icon: 'fail',
        content: '删除失败，请重试',
      }), () => message.error('删除失败，请重试'));
      return false;
    }
  }

  const columns: ProColumnType<any>[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 80,
      hideInSearch: true,
      hideInForm: true,
      hideInTable: mobileRender(windowWidth, true),
      fixed: 'left',
      render(dom, entity, index) {
        return index + 1;
      },
      editable: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
      fieldProps: {
        placeholder: '请输入名称'
      },
      renderFormItem: mobileRender(windowWidth, (schema: any, config: any, form: any, action: any) => <Input clearable />),
      render: mobileRender(windowWidth, (dom: any) => {
        return <MobileTableItem label='名称' value={dom} />
      }),
    },
    {
      title: 'Key',
      dataIndex: 'key',
      hideInSearch: true,
      fieldProps: {
        placeholder: '请输入Key'
      },
      renderFormItem: mobileRender(windowWidth, (schema: any, config: any, form: any, action: any) => <Input clearable />),
      render: mobileRender(windowWidth, (dom: any) => {
        return <MobileTableItem label='Key' value={dom} />
      }),
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record: any) => {
        return [
          <BetaSchemaForm<any>
            key="eidit"
            form={editForm}
            trigger={mobileRender(windowWidth, <Button block onClick={() => {
              setEditOpen(true)
              editForm.setFieldsValue({
                ...record,
              })
            }}>编辑</Button>, <a
              onClick={async () => {
                setEditOpen(true)
                editForm.setFieldsValue({
                  ...record,
                })
              }}
            >
              编辑
            </a>)}
            layoutType={'DrawerForm'}
            drawerProps={{
              width: 600,
              title: '编辑支付方式',
              destroyOnClose: true,
            }}
            submitter={{
              render: mobileRender(windowWidth, (props: any, doms: any) => {
                return [
                  <Button key={'resetFields'} block onClick={(e) => {
                    doms?.[0]?.props?.onClick?.(e)
                  }}>
                    取消
                  </Button>,
                  <Button key={'submit'} block color='primary' style={{ marginTop: 4 }} onClick={() => {
                    props.form?.submit?.()
                  }}>
                    提交
                  </Button>,
                ];
              }),
            }}
            onFinish={async (values) => {
              // console.log('values', values);
              const hide = mobileRun(windowWidth, () => Toast.show({
                icon: 'loading',
                content: '正在保存…',
              }), () => message.loading('正在保存'));

              try {
                const res = await updateArticle({
                  ...values,
                  id: record?.id,
                  status: Array.isArray(values?.status) ? +values?.status[values?.status.length - 1] : +values?.status,
                })
                if (typeof hide === 'function') {
                  hide();
                } else {
                  hide.close?.()
                }
                if (res?.code === 0) {
                  mobileRun(windowWidth, () => Toast.show({
                    icon: 'success',
                    content: '保存成功，即将刷新',
                  }), () => message.success('保存成功，即将刷新'));
                  actionRef.current?.reload()
                  return true;
                } else {
                  mobileRun(windowWidth, () => Toast.show({
                    icon: 'fail',
                    content: '保存失败，请重试',
                  }), () => message.error('保存失败，请重试'));
                  return false;
                }
              } catch (error) {
                if (typeof hide === 'function') {
                  hide();
                } else {
                  hide.close?.()
                }
                mobileRun(windowWidth, () => Toast.show({
                  icon: 'fail',
                  content: '保存失败，请重试',
                }), () => message.error('保存失败，请重试'));
                return false;
              }
            }}
            columns={columns as any}
          />,
          pcRender(windowWidth, <Popconfirm
            key="pc_del"
            title="删除支付方式"
            description={<>
              <p>确认删除 <b>{record?.name}</b> 支付方式?</p>
            </>}
            onConfirm={() => onDelRecordItem(record)}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>),
          mobileRender(windowWidth, <Button
            block
            key={'mobile_del'}
            onClick={() => {
              Dialog.confirm({
                title: '删除支付方式',
                content: <p>确认删除 <b>{record?.name}</b> 支付方式?</p>,
                onConfirm: async () => {
                  await onDelRecordItem(record)
                },
              })
            }}
          >
            删除
          </Button>)
        ];
      },
    },
  ];

  const onBatchDel = async () => {
    const onOk = async () => {
      const hide = mobileRun(windowWidth, () => Toast.show({
        icon: 'loading',
        content: '正在删除…',
      }), () => message.loading('正在删除'));

      try {
        const res = await batchDelArticle({
          ids: selectedRowsState?.map((item: any) => item.id)
        })
        if (typeof hide === 'function') {
          hide();
        } else {
          hide.close?.()
        }
        if (res.code === 0) {
          mobileRun(windowWidth, () => Toast.show({
            icon: 'success',
            content: '删除成功，即将刷新',
          }), () => message.success('删除成功，即将刷新'));
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.()
          return true
        } else {
          mobileRun(windowWidth, () => Toast.show({
            icon: 'fail',
            content: '删除失败，请重试',
          }), () => message.error('删除失败，请重试'));
          return false;
        }
      } catch (e) {
        if (typeof hide === 'function') {
          hide();
        } else {
          hide.close?.()
        }
        mobileRun(windowWidth, () => Toast.show({
          icon: 'fail',
          content: '删除失败，请重试',
        }), () => message.error('删除失败，请重试'));
        return false;
      }

    }
    mobileRun(windowWidth, () => Dialog.confirm({
      title: `确认删除 ${selectedRowsState?.length} 条数据?`,
      content: `请谨慎操作，删除后不可恢复`,
      onConfirm: async () => {
        await onOk()
      },
    }), () => Modal.confirm({
      title: `确认删除 ${selectedRowsState?.length} 条数据?`,
      content: `请谨慎操作，删除后不可恢复`,
      onOk
    }))
  }
  return (
    <PageContainer className='article_wrap'>
      <div ref={customTabRef}>
        <ProTable<TableListItem, TableListPagination>
          headerTitle={pcRender(windowWidth, "支付方式管理")}
          actionRef={actionRef}
          rowKey="id"
          options={mobileRender(windowWidth, false)}
          search={{
            labelWidth: 120,
            className: 'search_filter',
            layout: 'vertical',
            optionRender: mobileRender(windowWidth, (searchConfig: any) => [
              <Button key={'resetFields'} block onClick={() => {
                searchConfig?.form?.resetFields()
                searchConfig?.form?.submit()
              }}>
                重置
              </Button>,
              <Button key={'submit'} block color='primary' style={{ marginTop: 4 }} onClick={() => {
                searchConfig?.form?.submit()
              }}>
                查询
              </Button>,
            ])
          }}
          scroll={pcRender(windowWidth, { x: 'max-content' })}
          toolBarRender={() => [
            <BetaSchemaForm<any>
              key={'add'}
              open={addOpen}
              trigger={mobileRender(windowWidth, <Button
                key="primary"
                block
                onClick={() => {
                  setAddOpen(true)
                  addForm.resetFields()
                  addForm.setFieldValue('openMethod', "_blank")
                }}
              >
                <PlusOutlined /> 新建
              </Button>) || <PCButton
                type="primary"
                key="primary"
                onClick={() => {
                  addForm.resetFields()
                  addForm.setFieldValue('openMethod', "_blank")
                }}
              >
                  <PlusOutlined /> 新建
                </PCButton>}
              form={addForm}
              layoutType={'DrawerForm'}
              submitter={{
                render: mobileRender(windowWidth, (props: any, doms: any) => {
                  return [
                    <Button key={'resetFields'} block onClick={() => {
                      setAddOpen(false)
                    }}>
                      取消
                    </Button>,
                    <Button key={'submit'} block color='primary' style={{ marginTop: 4 }} onClick={() => {
                      props.form?.submit?.()
                    }}>
                      提交
                    </Button>,
                  ];
                }),
              }}
              drawerProps={{
                width: 600,
                title: '新增支付方式',
                destroyOnClose: true,
                onClose() {
                  setAddOpen(false)
                },
              }}
              onFinish={async (values) => {
                // console.log('values', values);

                const hide = mobileRun(windowWidth, () => Toast.show({
                  icon: 'loading',
                  content: '正在保存…',
                }), () => message.loading('正在保存'));

                try {
                  const res = await addArticle({
                    ...values,
                    targetProfessionalTitle: Array.isArray(values?.targetProfessionalTitle) ? values?.targetProfessionalTitle[values?.targetProfessionalTitle.length - 1] : values?.targetProfessionalTitle,
                    workUnitId: Array.isArray(values?.workUnitId) ? values?.workUnitId[values?.workUnitId.length - 1] : values?.workUnitId,
                    provinceId: Array.isArray(values?.provinceId) ? values?.provinceId[values?.provinceId.length - 1] : values?.provinceId,
                    inclusionRequirements: Array.isArray(values?.inclusionRequirements) ? values?.inclusionRequirements[values?.inclusionRequirements.length - 1] : values?.inclusionRequirements,
                    price: Array.isArray(values?.price) ? values?.price[values?.price.length - 1] : values?.price,
                    reviewTime: dayjs(values?.reviewTime).format("YYYY-MM-DD HH:mm:ss"),
                  })
                  if (typeof hide === 'function') {
                    hide();
                  } else {
                    hide.close?.()
                  }
                  if (res?.code === 0) {
                    mobileRun(windowWidth, () => Toast.show({
                      icon: 'success',
                      content: '保存成功，即将刷新',
                    }), () => message.success('保存成功，即将刷新'));
                    actionRef.current?.reload()
                    return true;
                  } else {
                    mobileRun(windowWidth, () => Toast.show({
                      icon: 'fail',
                      content: '保存失败，请重试',
                    }), () => message.error('保存失败，请重试'));
                    return false;
                  }
                } catch (error) {
                  if (typeof hide === 'function') {
                    hide();
                  } else {
                    hide.close?.()
                  }
                  mobileRun(windowWidth, () => Toast.show({
                    icon: 'fail',
                    content: '保存失败，请重试',
                  }), () => message.error('保存失败，请重试'));
                  return false;
                }
              }}
              columns={columns as any}
            />
            ,
          ]}
          request={async ({ current, pageSize, ...other }) => {
            const res = await getPayMethodPage({
              page: current,
              size: pageSize,
              keywords: (other as any)?.name
            })

            return {
              total: res?.data?.total,
              data: res?.data?.items?.map((item: any) => ({
                ...item,
                status: item?.status + '',
                createdAt: dayjs.unix(item.createdAt).format('YYYY-MM-DD HH:mm:ss')
              }))
            }
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
          id='custom-table'
          className={'custom-table'}
          components={mobileRender(windowWidth, {
            header: {
              row: () => <></>
            },
            body: {
              row: CustomRow
            }
          })}
        />
      </div>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div style={mobileRender(windowWidth, { fontSize: 17 })}>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState?.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          {mobileRender(windowWidth, <Button
            onClick={onBatchDel}
          >
            批量删除
          </Button>, <PCButton
            onClick={onBatchDel}
          >
            批量删除
          </PCButton>)}
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
